// pages/addPost/addPost.js
//获取全局变量
var app = getApp()

import util from '../../utils/utils';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasImage: false,
    imageUrl: "",
    lastId: 1
  },

  imageSelect: function () {
    wx.chooseImage({
      count: 1,
      success: (res) => {
        const tempFilePaths = res.tempFilePaths
        this.setData({
          hasImage: true,
          imageUrl: tempFilePaths[0]
        })
      },
    })
  },

  notimageSelect: function () {
    this.setData({
      hasImage: false,
      imageUrl: ""
    })
  },

  bindFormSubmit: function (e) {
    let {
      textarea
    } = e.detail.value;
    if (this.data.hasImage) {
      wx.uploadFile({
        url: 'http://120.24.97.106:8081/uploadImage', 
        filePath: this.data.imageUrl,
        name: 'file',
        formData: {
          imageName: this.data.lastId + ""
        },
        success(res) {
          console.log(res.data)
        }
      })

      //获取时间
      var time = util.formatTime(new Date());
      wx.request({
        url: 'http://120.24.97.106:8081/savePost',
        method: 'POST',
        data: {
          "id": this.data.lastId,
          "userid": app.userid,
          "nickname": app.nickName,
          "avatarUrl": app.avatarUrl,
          "releasetime": time,
          "texts": textarea,
          "image": "http://120.24.97.106:8080/image/" + this.data.lastId + ".png",
          "pageviews": 0,
          "likes": 0,
          "commentvolume": 0,
          "haslike":false
        },
        success: (result) => {
          app.hasAddPost=true
          wx.showLoading({
            title: '发布中',
          })
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
            wx.hideLoading()
          }, 1500)
        }
      });


    } else {
      wx.showToast({
        title: '图片选一张呗~',
        icon: 'none',
        image: '',
        duration: 1500,
      });
    }

  },

  to_p1: function () {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获得post表中最后一行的id,然后加1
    wx.request({
      url: 'http://120.24.97.106:8081/getLastId',
      method: 'GET',
      success: (result) => {
        const x = result.data + 1
        this.setData({
          lastId: x
        })
      }
    })



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})